package com.future.message.configuration.Filter;

import com.future.message.Service.UserService;
import com.future.message.configuration.Security.TokenManager;
import com.future.message.pojo.SecurityUser;
import lombok.SneakyThrows;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

/**
 * @description:
 * @projectName:message
 * @see:com.future.message.configuration.Filter
 * @author:Xuyujie
 * @createTime:2021/12/5 22:37
 * @version:1.0
 */
public class TokenAuthFilter extends BasicAuthenticationFilter {

    private TokenManager tokenManager;

    private UserService userService;

    public TokenAuthFilter(AuthenticationManager authenticationManager, TokenManager tokenManager,UserService userService) {
        super(authenticationManager);
        this.tokenManager = tokenManager;
        this.userService = userService;
    }

    @SneakyThrows
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取成功认证的用户权限信息
        UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
        //判断如果有权限信息放入上下文
        if (authentication != null){
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }else{
            SecurityContextHolder.getContext().setAuthentication(null);
        }
        chain.doFilter(request,response);
    }

    /**
     * 获取权限信息
     * @param request
     * @return
     */
    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request)  {
        String token = request.getHeader("token");
        if (token != null && tokenManager.verfyToken(token)){
            //获取用户登录的用户名
            String username = tokenManager.getUserInfoFromToken(token);
            if (username == null){
                return null;
            }
            //从数据库获得用户权限
            SecurityUser securityUser = userService.queryByUserName(username);
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("ROLE_"+securityUser.getCurrentUserInfo().getGrade()));
            return new UsernamePasswordAuthenticationToken(securityUser,token,authorities);
        }
        //返回null
        return null;
    }
}
